<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>视频查看 - 管理员</title>
    <link rel="stylesheet" href="../css/common.css">
    <style>
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        .page-header {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            color: white;
            padding: 30px;
            border-radius: 15px;
            margin-bottom: 30px;
            text-align: center;
        }

        .page-title {
            font-size: 2.5em;
            margin: 0;
            font-weight: 300;
        }

        .page-subtitle {
            font-size: 1.1em;
            margin: 10px 0 0 0;
            opacity: 0.9;
        }

        .video-container {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 30px;
            margin-bottom: 30px;
        }

        .video-player-section {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .video-player-container {
            width: 100%;
            background: #000;
            border-radius: 8px;
            overflow: hidden;
            position: relative;
            min-height: 300px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 20px;
        }

        .video-player {
            width: 100%;
            height: auto;
            max-height: 400px;
        }

        .video-loading {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: #666;
            font-size: 16px;
        }

        .video-loading i {
            font-size: 32px;
            margin-bottom: 10px;
        }

        .video-error {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: #666;
            text-align: center;
            padding: 20px;
        }

        .video-error i {
            font-size: 48px;
            margin-bottom: 15px;
        }

        .video-error h3 {
            margin: 0 0 10px 0;
            color: #333;
        }

        .video-error p {
            margin: 0;
            color: #666;
        }

        .video-info {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .video-title {
            font-size: 1.8em;
            font-weight: 600;
            color: #333;
            margin-bottom: 15px;
        }

        .video-meta {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
            margin-bottom: 20px;
        }

        .meta-item {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 8px;
        }

        .meta-label {
            font-weight: 500;
            color: #666;
        }

        .meta-value {
            color: #333;
        }

        .video-description {
            color: #666;
            line-height: 1.6;
            margin-bottom: 20px;
        }

        .video-actions {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }

        .btn-action {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1em;
            font-weight: 500;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background: #dc3545;
            color: white;
        }

        .btn-primary:hover {
            background: #c82333;
            transform: translateY(-2px);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #5a6268;
            transform: translateY(-2px);
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-success:hover {
            background: #218838;
            transform: translateY(-2px);
        }

        .btn-warning {
            background: #ffc107;
            color: #212529;
        }

        .btn-warning:hover {
            background: #e0a800;
            transform: translateY(-2px);
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-danger:hover {
            background: #c82333;
            transform: translateY(-2px);
        }

        .admin-actions {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }

        .section-title {
            font-size: 1.5em;
            color: #333;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #f0f0f0;
        }

        .admin-actions-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
        }

        .btn-admin {
            padding: 15px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1em;
            font-weight: 500;
            transition: all 0.3s ease;
            text-align: center;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 8px;
        }

        .btn-admin:hover {
            transform: translateY(-2px);
        }

        .btn-approve {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .btn-reject {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .btn-edit {
            background: #cce5ff;
            color: #004085;
            border: 1px solid #b3d7ff;
        }

        .btn-delete {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .btn-download {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }

        .btn-stats {
            background: #e2e3e5;
            color: #383d41;
            border: 1px solid #d6d8db;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .loading-spinner {
            display: inline-block;
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #dc3545;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .error-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }

        .error-icon {
            font-size: 4em;
            margin-bottom: 20px;
            opacity: 0.5;
        }

        .error-title {
            font-size: 1.5em;
            margin-bottom: 10px;
            color: #333;
        }

        .error-description {
            font-size: 1em;
            line-height: 1.5;
        }

        .status-badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8em;
            font-weight: 600;
            text-transform: uppercase;
        }

        .status-pending {
            background: #fff3cd;
            color: #856404;
        }

        .status-approved {
            background: #d4edda;
            color: #155724;
        }

        .status-rejected {
            background: #f8d7da;
            color: #721c24;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar">
        <div class="nav-container">
            <div class="nav-brand">
                <span class="brand-icon">🎓</span>
                <span class="brand-text">学习平台</span>
            </div>
            <div class="nav-menu">
                <a href="dashboard.html" class="nav-link">
                    <span class="nav-icon">🏠</span>
                    <span class="nav-text">首页</span>
                </a>
                <a href="videos.html" class="nav-link">
                    <span class="nav-icon">📹</span>
                    <span class="nav-text">视频管理</span>
                </a>
                <a href="exam-management.html" class="nav-link">
                    <span class="nav-icon">📝</span>
                    <span class="nav-text">考试管理</span>
                </a>
                <a href="users.html" class="nav-link">
                    <span class="nav-icon">👥</span>
                    <span class="nav-text">用户管理</span>
                </a>
            </div>
            <div class="nav-user">
                <span class="user-info" id="userInfo">加载中...</span>
                <button class="btn-logout" onclick="logout()">退出</button>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="page-header">
            <h1 class="page-title">📹 视频查看</h1>
            <p class="page-subtitle">管理员视频审核和管理</p>
        </div>

        <div id="loadingState" class="loading">
            <div class="loading-spinner"></div>
            <p>正在加载视频...</p>
        </div>

        <div id="errorState" class="error-state" style="display: none;">
            <div class="error-icon">❌</div>
            <h3 class="error-title">视频加载失败</h3>
            <p class="error-description" id="errorMessage">请检查视频是否存在或权限是否正确</p>
        </div>

        <div id="videoContent" style="display: none;">
            <!-- 管理员专用操作区域 -->
            <div class="admin-actions">
                <h2 class="section-title">🔧 管理员操作</h2>
                <div class="admin-actions-grid">
                    <button class="btn-admin btn-approve" onclick="approveVideo()">
                        <span style="font-size: 1.5em;">✅</span>
                        <span>审核通过</span>
                    </button>
                    <button class="btn-admin btn-reject" onclick="rejectVideo()">
                        <span style="font-size: 1.5em;">❌</span>
                        <span>审核拒绝</span>
                    </button>
                    <button class="btn-admin btn-edit" onclick="editVideo()">
                        <span style="font-size: 1.5em;">✏️</span>
                        <span>编辑信息</span>
                    </button>
                    <button class="btn-admin btn-delete" onclick="deleteVideo()">
                        <span style="font-size: 1.5em;">🗑️</span>
                        <span>删除视频</span>
                    </button>
                    <button class="btn-admin btn-download" onclick="downloadVideo()">
                        <span style="font-size: 1.5em;">📥</span>
                        <span>下载视频</span>
                    </button>
                    <button class="btn-admin btn-stats" onclick="viewVideoStats()">
                        <span style="font-size: 1.5em;">📊</span>
                        <span>查看统计</span>
                    </button>
                </div>
            </div>

            <div class="video-container">
                <div class="video-player-section">
                    <div id="videoPlayerContainer" class="video-player-container">
                        <!-- 视频播放器将在这里生成 -->
                    </div>
                </div>

                <div class="video-info">
                    <h2 class="video-title" id="videoTitle">视频标题</h2>
                    
                    <div class="video-meta">
                        <div class="meta-item">
                            <span class="meta-label">上传者:</span>
                            <span class="meta-value" id="uploaderName">未知</span>
                        </div>
                        <div class="meta-item">
                            <span class="meta-label">上传时间:</span>
                            <span class="meta-value" id="uploadTime">未知</span>
                        </div>
                        <div class="meta-item">
                            <span class="meta-label">观看次数:</span>
                            <span class="meta-value" id="viewCount">0</span>
                        </div>
                        <div class="meta-item">
                            <span class="meta-label">审核状态:</span>
                            <span class="meta-value" id="approvalStatus">未知</span>
                        </div>
                        <div class="meta-item">
                            <span class="meta-label">文件大小:</span>
                            <span class="meta-value" id="fileSize">未知</span>
                        </div>
                        <div class="meta-item">
                            <span class="meta-label">视频时长:</span>
                            <span class="meta-value" id="duration">未知</span>
                        </div>
                    </div>

                    <div class="video-description" id="videoDescription">
                        视频描述信息...
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="../js/common.js"></script>
    <script>
        let currentVideo = null;
        let currentUser = null;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkAuth();
            loadVideo();
        });

        // 检查用户认证状态
        function checkAuth() {
            currentUser = UserManager.getCurrentUser();
            if (!currentUser || currentUser.role !== 0) {
                Message.error('请先登录管理员账号');
                setTimeout(() => {
                    window.location.href = '../login.html';
                }, 1500);
                return;
            }
            document.getElementById('userInfo').textContent = `欢迎，${currentUser.name}`;
        }

        // 加载视频
        async function loadVideo() {
            const urlParams = new URLSearchParams(window.location.search);
            const videoId = urlParams.get('id');
            
            if (!videoId) {
                showError('视频ID不存在');
                return;
            }

            try {
                const response = await API.get(`/video/admin/${videoId}`);
                if (response.success) {
                    currentVideo = response.video;
                    renderVideo();
                } else {
                    showError(response.message || '视频加载失败');
                }
            } catch (error) {
                console.error('加载视频失败:', error);
                showError('视频加载失败，请稍后重试');
            }
        }

        // 渲染视频
        function renderVideo() {
            if (!currentVideo) return;

            const playerContainer = document.getElementById('videoPlayerContainer');

            // 显示加载状态
            playerContainer.innerHTML = `
                <div class="video-loading">
                    <i>⏳</i>
                    <span>正在加载视频...</span>
                </div>
            `;

            try {
                // 直接使用视频流URL
                const streamUrl = `/api/video/stream/${currentVideo.id}`;
                
                // 创建视频播放器
                const videoElement = document.createElement('video');
                videoElement.className = 'video-player';
                videoElement.controls = true;
                videoElement.preload = 'metadata';
                videoElement.src = streamUrl;
                
                // 视频加载事件
                videoElement.addEventListener('loadedmetadata', () => {
                    playerContainer.innerHTML = '';
                    playerContainer.appendChild(videoElement);
                });
                
                // 视频播放结束事件
                videoElement.addEventListener('ended', () => {
                    console.log('管理员端视频播放结束');
                    // 管理员端不需要记录学习进度，只需要记录观看
                });

                // 视频错误处理
                videoElement.addEventListener('error', (e) => {
                    console.error('视频播放错误:', e);
                    console.error('错误详情:', {
                        error: videoElement.error,
                        networkState: videoElement.networkState,
                        readyState: videoElement.readyState,
                        src: videoElement.src,
                        currentSrc: videoElement.currentSrc,
                        currentTime: videoElement.currentTime,
                        duration: videoElement.duration
                    });
                    
                    let errorMessage = '视频播放失败';
                    let errorDetail = '请检查网络连接或联系管理员';
                    let showError = true;
                    
                    if (videoElement.error) {
                        switch (videoElement.error.code) {
                            case 1:
                                errorMessage = '视频加载被中止';
                                errorDetail = '网络连接中断或服务器响应超时';
                                break;
                            case 2:
                                errorMessage = '网络错误';
                                errorDetail = '无法连接到视频服务器';
                                break;
                            case 3:
                                errorMessage = '视频解码错误';
                                errorDetail = '视频格式不支持或文件损坏';
                                // 如果是播放结束后的解码错误，可能是正常的
                                if (videoElement.currentTime > 0 && videoElement.duration > 0 && 
                                    Math.abs(videoElement.currentTime - videoElement.duration) < 1) {
                                    console.log('检测到播放结束后的解码错误，可能是正常的');
                                    showError = false;
                                }
                                break;
                            case 4:
                                errorMessage = '视频格式不支持';
                                errorDetail = '浏览器不支持此视频格式';
                                break;
                            default:
                                errorMessage = '未知播放错误';
                                errorDetail = `错误代码: ${videoElement.error.code}`;
                        }
                    }
                    
                    // 只有在需要显示错误的情况下才显示错误界面
                    if (showError) {
                        playerContainer.innerHTML = `
                            <div class="video-error">
                                <i>❌</i>
                                <h3>${errorMessage}</h3>
                                <p>${errorDetail}</p>
                                <div style="margin-top: 16px;">
                                    <button class="btn btn-primary" onclick="location.reload()">重新加载</button>
                                    <button class="btn btn-secondary" onclick="window.history.back()">返回</button>
                                </div>
                            </div>
                        `;
                    }
                });
            } catch (error) {
                console.error('获取视频流失败:', error);
                playerContainer.innerHTML = `
                    <div class="video-error">
                        <i>❌</i>
                        <h3>视频加载失败</h3>
                        <p>网络错误，无法连接到服务器</p>
                    </div>
                `;
            }

            // 设置视频信息
            document.getElementById('videoTitle').textContent = currentVideo.title;
            document.getElementById('uploaderName').textContent = currentVideo.uploaderName || '未知';
            document.getElementById('uploadTime').textContent = formatDate(currentVideo.uploadTime);
            document.getElementById('viewCount').textContent = currentVideo.viewCount || 0;
            document.getElementById('fileSize').textContent = formatFileSize(currentVideo.fileSize);
            document.getElementById('duration').textContent = formatDuration(currentVideo.duration);
            document.getElementById('videoDescription').textContent = currentVideo.intro || '暂无描述';

            // 设置审核状态
            const statusElement = document.getElementById('approvalStatus');
            const statusText = getApprovalStatusText(currentVideo.approved);
            const statusClass = getApprovalStatusClass(currentVideo.approved);
            statusElement.innerHTML = `<span class="status-badge ${statusClass}">${statusText}</span>`;

            document.getElementById('loadingState').style.display = 'none';
            document.getElementById('videoContent').style.display = 'block';
        }

        // 显示错误状态
        function showError(message) {
            document.getElementById('loadingState').style.display = 'none';
            document.getElementById('errorMessage').textContent = message;
            document.getElementById('errorState').style.display = 'block';
        }

        // 获取审核状态文本
        function getApprovalStatusText(approved) {
            switch (approved) {
                case 0: return '待审核';
                case 1: return '已通过';
                case 2: return '已拒绝';
                default: return '未知';
            }
        }

        // 获取审核状态样式类
        function getApprovalStatusClass(approved) {
            switch (approved) {
                case 0: return 'status-pending';
                case 1: return 'status-approved';
                case 2: return 'status-rejected';
                default: return 'status-pending';
            }
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '未知';
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (!bytes) return '未知';
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(1024));
            return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
        }

        // 格式化时长
        function formatDuration(seconds) {
            if (!seconds) return '未知';
            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            const secs = seconds % 60;
            
            if (hours > 0) {
                return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
            } else {
                return `${minutes}:${secs.toString().padStart(2, '0')}`;
            }
        }

        // 审核通过
        async function approveVideo() {
            if (!confirm('确定要审核通过这个视频吗？')) {
                return;
            }

            try {
                const response = await API.put(`/video/admin/approve/${currentVideo.id}`, {});
                if (response.success) {
                    Message.success('视频审核通过');
                    currentVideo.approved = 1;
                    renderVideo();
                } else {
                    Message.error(response.message || '审核失败');
                }
            } catch (error) {
                console.error('审核视频失败:', error);
                Message.error('审核失败，请稍后重试');
            }
        }

        // 审核拒绝
        async function rejectVideo() {
            const reason = prompt('请输入拒绝原因：');
            if (!reason) return;

            try {
                const response = await API.put(`/video/admin/reject/${currentVideo.id}`, {
                    reason: reason
                });
                if (response.success) {
                    Message.success('视频审核拒绝');
                    currentVideo.approved = 2;
                    renderVideo();
                } else {
                    Message.error(response.message || '审核失败');
                }
            } catch (error) {
                console.error('审核视频失败:', error);
                Message.error('审核失败，请稍后重试');
            }
        }

        // 编辑视频
        function editVideo() {
            // 暂时跳转到视频管理页面，因为编辑页面尚未实现
            window.location.href = 'videos.html';
        }

        // 删除视频
        async function deleteVideo() {
            if (!confirm('确定要删除这个视频吗？删除后无法恢复。')) {
                return;
            }

            try {
                const response = await API.delete(`/video/admin/delete/${currentVideo.id}`);
                if (response.success) {
                    Message.success('视频删除成功');
                    setTimeout(() => {
                        window.location.href = 'videos.html';
                    }, 1500);
                } else {
                    Message.error(response.message || '删除失败');
                }
            } catch (error) {
                console.error('删除视频失败:', error);
                Message.error('删除失败，请稍后重试');
            }
        }

        // 下载视频
        function downloadVideo() {
            const link = document.createElement('a');
            link.href = `/videos/${currentVideo.path}`;
            link.download = currentVideo.title + '.mp4';
            link.click();
        }

        // 查看视频统计
        function viewVideoStats() {
            window.open(`video-stats.html?id=${currentVideo.id}`, '_blank');
        }

        // 退出登录
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                UserManager.logout();
                window.location.href = '../login.html';
            }
        }
    </script>
</body>
</html>
